﻿<?php
     require("dbConnect.php");
     require("function.php");
     
     $files = array();
     $createFlg = array();
     $size  = 0;
     $pathErr = False;
     $fileCreateErr = False;
     $webCreateErr = False;
     $newFileName = "";
     $fileDeleteErr = False;
     $deleteFileName = "";
     $modifyConfigErr = False;
     $addViewErr = False;
     $delViewErr = False;
     $queryWebErr = False;
     $webResult = null;
     
     if (!$dbConnectErr && !$pathErr && isset($_REQUEST['operate'])) {
          // 通过$_REQUEST['operate']区分操作类型
          if ($_REQUEST['operate'] == "cretate") {
              // 新增站点
              $newFileName = $_REQUEST['dAaFileName'];
              createWebSite();
          } else if ($_REQUEST['operate'] == "delete"){
              // 获得删除文件名称并删除文件
              $deleteFileName = $_REQUEST['dAaFileName'];
              deleteWebSite();
          } else if ($_REQUEST['operate'] == "add") {
             // 获取文件名并创建
              $newFileName = $_REQUEST['dAaFileName'];
              addWebSite();
          }    
     }
        
     if (!$dbConnectErr) {
        $sql = "select * from website_tbl order by webID";
        $webResult = mysql_query($sql);
        if (!$webResult) {
          $queryWebErr = True;
        } else {
            $count = 0;
            while (list($webID, $cFlg) = mysql_fetch_row($webResult)) {
                $files[$count] = $webID;
                $createFlg[$count] = $cFlg;
                $count++;
            }
            $size = sizeof($files);
        }
        
     }
     
     // 表中添加子站点
     function createWebSite() {
        global $newFileName,$webCreateErr;
        $sql = "insert into website_tbl(webID) values('${newFileName}')";
        if (!mysql_query($sql)) {
             $webCreateErr = True;
        }
     }
         
     // 创建视图文件
     function addWebSite() {
        global $size,$files,$fileCreateErr,$newFileName,$addViewErr;
       
        // 父站点路径
        $souceFile = TEMPLEPATH.TEMPLEFILENAME;
        // 新增子站点路径
        $destination = WEBSITEPATH.$newFileName;
        
        // 设置操作超时时间(文件复制需要4~5分钟)
        set_time_limit(LIMITTIME);
        
        // 执行文件复制操作
        if (!xCopy($souceFile, $destination, 1)) {
           $fileCreateErr = True;
        }
        
        // 修改配置文件
        if (!$fileCreateErr) {
          $configFile = $destination."\config\config.php";
           if (!file_exists( $configFile)) {
              $modifyConfigErr = True;
           } else {
              try {
                 $filec = file_get_contents($configFile);
                 $temText = preg_replace("/define\('DB_PREFIX'.*\)/", "define('DB_PREFIX', '${newFileName}_')", $filec);
                 $fileo=fopen($configFile,"w"); 
                 fwrite($fileo,$temText);
                fclose($fileo);
              }catch(Exception $e) {
                 $modifyConfigErr = True;
             }
          }
       } 
 
        // 创建视图
        $tables = mysql_list_tables(DB_NAME);
        $excTables = array(DB_PREFIX."goods",DB_PREFIX."products","website_tbl");
        
        // 启动事务
        mysql_query("BEGIN TRANSACTION DEPS02_DEL");
        
        try {
            // 表前缀的长度
            $pos = strlen(DB_PREFIX);
            
            while (list($tableName) = mysql_fetch_row($tables)) {   
                if (!in_array($tableName,$excTables) && substr($tableName,0,$pos) == DB_PREFIX) {
                     $viewName = $newFileName.substr($tableName,$pos-1);
                     $sql = "create or replace view ${viewName} as select * from ${tableName}";
                      
                     if (!mysql_query($sql)) {
                         $addViewErr = True;
                         break;
                     }
                 }
            }
            
            $excFields = array("price");
            $sqlFields = array();
            $idFields = array("goods_id","product_id");
            // 拼接视图字段
            for ($j=0; $j<2; $j++){
                 $fields = mysql_list_fields(DB_NAME, $excTables[$j]);
                 $col = mysql_num_fields($fields);
                 
                 for ($k=0; $k<$col; $k++) {
                    $fieldName = mysql_field_name($fields,$k);
					if($fieldName=="store") continue;
                    if (in_array($fieldName, $excFields)) {
                        $t = "b.";  
                    } else {
                        $t = "a.";
                    }
                    $sqlFields[$j] = $sqlFields[$j].$t.$fieldName." ".$fieldName.", ";
                 }
                 $sqlFields[$j]=$sqlFields[$j]."b.Quantity as store, ";
                 $flen = strlen($sqlFileds[$j]);
                 $sqlFields[$j] = substr($sqlFields[$j],0,$flen-2);
            }
            
            // 为goods，puducts表创建新表和视图
            for ($i=0; $i<2 && !$addViewErr; $i++) {
                 $newTable = $newFileName.substr($excTables[$i],$pos-1).DB_SUFFIX;
      
                 mysql_query("drop table ${newTable} ");
                 $sql = "create table ${newTable} 
                           ({$idFields[$i]} mediumint(8) primary key, 
						   Quantity decimal(20,0) not null,
                            price decimal(20,3) not null
                            )";
                 
                 if (!mysql_query($sql)) {
                      $addViewErr = True;
                 } else {
                    $viewName = $newFileName.substr($excTables[$i],$pos-1);
                    $sql = "create or replace view ${viewName} 
                            as select {$sqlFields[$i]} from {$excTables[$i]} a, ${newTable} b 
                            where a.{$idFields[$i]} = b.{$idFields[$i]}";
                    if (!mysql_query($sql)) {
                       $addViewErr = True;
                    }
                 }
            }
            
            if (!$addViewErr) {
                 $sql = "update website_tbl set created = '1' where webID = '${newFileName}'";
                 if (!mysql_query($sql)){
                     $addViewErr = True;
                 }
            }
        }catch(exception $e) {
              $addViewErr = True;
        }

       if(!$addViewErr){    
            mysql_query("COMMIT TRANSACTION DEPS02_DEL"); // 提交事务
       }else{
            mysql_query("ROLLBACK TRANSACTION DEPS02_DEL"); // 回滚事务
       }
        
        // 重新获取文件名
        //getFiles(&$files,&$size);
     }
     
     
     function deleteWebSite() {
        global $size,$files,$fileDeleteErr,$deleteFileName;$delViewErr;
        // 删除文件路径
        $deleteFile = WEBSITEPATH.$deleteFileName;
        // 设置操作超时时间
        set_time_limit(LIMITTIME);
        
        // 执行文件删除操作
        if(!deldir($deleteFile)) {
           $fileDeleteErr = True;
        }
       
        // 启动事务
        mysql_query("BEGIN TRANSACTION DEPS02_DEL");
        // 删除视图，表
        $tables = mysql_list_tables(DB_NAME);
        $excTables = array(DB_PREFIX."goods",DB_PREFIX."products","website_tbl");
        
        try {
            // 表前缀的长度
            $pos = strlen(DB_PREFIX);
   
            while (list($tableName) = mysql_fetch_row($tables)) {   
                if (!in_array($tableName,$excTables) && substr($tableName,0,$pos) == DB_PREFIX) {
                     $viewName = $deleteFileName.substr($tableName,$pos-1);
                     $sql = "drop view ${viewName}";
                     if (!mysql_query($sql)) {
                         $delViewErr = True;
                         break;
                     }
                 }
            }
         
            // 删除goods，puducts表和视图
            for ($i=0; $i<2 && !$delViewErr; $i++) {
                 $newTable = $deleteFileName.substr($excTables[$i],$pos-1).DB_SUFFIX;
    
                 $sql = "drop table ${newTable} ";
                 
                 if (!mysql_query($sql)) {
                      $delViewErr = True;
                 } else {
                    $viewName = $deleteFileName.substr($excTables[$i],$pos-1);
                    $sql = "drop view ${viewName}"; 
                    
                    if (!mysql_query($sql)) {
                       $delViewErr = True;
                    }
                 }
            }
           
            // 删除website_tbl中的记录
            $sql= "delete from website_tbl where webID = '${deleteFileName}'";
            if (!mysql_query($sql)) {
               $delViewErr = True;
            }
              
                     
        }catch(exception $e) {
              $delViewErr = True;
        }

       if(!$delViewErr){    
            mysql_query("COMMIT TRANSACTION DEPS02_DEL"); // 提交事务
       }else{
            mysql_query("ROLLBACK TRANSACTION DEPS02_DEL"); // 回滚事务
       }
     }
     
     function createTitle(){
         echo("<TR>
                    <TH class=gridViewHeader style='WIDTH: 0px;display:none;' scope=col>&nbsp;</TH>
                    <TH class=gridViewHeader scope=col>子站点名称</TH>
                    <TH class=gridViewHeader scope=col>删除</TH>
                    <TH class=gridViewHeader scope=col>添加</TH>
               </TR>");
     }

     function createRow($siteName, $dFlg) {
 
         echo("<TR>
                  <TD class=gridViewItem style='WIDTH: 0px;display:none;'> </TD>
                  <TD class=gridViewItem>${siteName}</TD>
                  <TD class=gridViewItem> 
                  <INPUT type='button' value='删除' onclick='deleteWebSite()'/>
                  </TD> 
                  <TD class=gridViewItem>");
         if (!$dFlg) {
              echo("<INPUT type='button' value='添加' onclick='createWebSite()'/>"); 
         }
                  	
         echo("
                </TD>
               </TR>");
    }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Untitled Page</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<STYLE type=text/css> 
{
	FONT-SIZE: 12px
}
.gridView {
	BORDER-RIGHT: #bad6ec 1px; BORDER-TOP: #bad6ec 1px; BORDER-LEFT: #bad6ec 1px; COLOR: #566984; BORDER-BOTTOM: #bad6ec 1px; FONT-FAMILY: Courier New; FONT-SIZE:12px
}
.gridViewHeader {
	BORDER-RIGHT: #bad6ec 1px solid; BORDER-TOP: #bad6ec 1px solid; BACKGROUND-IMAGE: url(../images/bg_th.gif); BORDER-LEFT: #bad6ec 1px solid; LINE-HEIGHT: 22px; BORDER-BOTTOM: #bad6ec 1px solid
}
.gridViewItem {
	BORDER-RIGHT: #bad6ec 1px solid; BORDER-TOP: #bad6ec 1px solid; BORDER-LEFT: #bad6ec 1px solid; LINE-HEIGHT: 22px; BORDER-BOTTOM: #bad6ec 1px solid; TEXT-ALIGN: center
}
.cmdField {
	BORDER-RIGHT: 0px; BORDER-TOP: 0px; BACKGROUND-IMAGE: url(../images/bg_rectbtn.png); OVERFLOW: hidden; BORDER-LEFT: 0px; WIDTH: 67px; COLOR: #364c6d; LINE-HEIGHT: 27px; BORDER-BOTTOM: 0px; BACKGROUND-REPEAT: repeat-x; HEIGHT: 27px; BACKGROUND-COLOR: transparent; TEXT-DECORATION: none
}
.buttonBlue {
	BORDER-RIGHT: 0px; BORDER-TOP: 0px; BACKGROUND-IMAGE: url(../images/bg_button_blue.gif); BORDER-LEFT: 0px; WIDTH: 78px; COLOR: white; BORDER-BOTTOM: 0px; BACKGROUND-REPEAT: no-repeat; HEIGHT: 21px
}
</STYLE>
<META content="MSHTML 6.00.2900.5848" name=GENERATOR>
   <script type="text/javascript">
        function deleteWebSite(){
        	 if (!confirm("确定要删除该站点吗？")){
        	     return;
        	 }
        	 
        	 showLoading();
        	 
           var obj = event.srcElement? event.srcElement:event.target;
           var row = obj.parentElement.parentElement;
           var sTd = row.cells[1];
           var siteName = sTd.innerText;
           
           document.getElementById("dAaFileName").value = siteName;
           document.getElementById("operate").value = "delete";
           document.forms["websiteForm"].submit();                  	
        }
        
        function createWebSite(){
        	 showLoading();
        	 
           var obj = event.srcElement? event.srcElement:event.target;
           var row = obj.parentElement.parentElement;
           var sTd = row.cells[1];
           var siteName = sTd.innerText;
           
           document.getElementById("dAaFileName").value = siteName;
           document.getElementById("operate").value = "add";
           document.forms["websiteForm"].submit();                  	
        }
        
      function checkLogin() {
        if (top == self){
      	   alert("还没登陆，请登陆");
      	   location.href = 'login.php';
        }	
      }
      
      function showLoading() {
          var dBody = top.document.body;
          var loading = top.document.createElement("div");
          loading.id = "loading";
          top.document.body.appendChild(loading);
          loading.style.cssText = "filter:alpha(opacity=30);position:absolute;top:0;left:0;z-index:100;background:#9D9D9D url(../images/loading.gif) center no-repeat;";
          loading.style.width = dBody.clientWidth;
          loading.style.height =dBody.clientHeight;
          loading.style.display = "block";
     }
     
     function reMoveLoading() {
          var elemtent = top.document.all("loading");
          if (elemtent) {
              top.document.body.removeChild(elemtent);
          }
     }
     
     function inputName() {
        var retValue = window.showModalDialog("inputName.htm", self, "dialogHeight:200px;dialogWidth:300px;resizable:no;scroll:yes;status:no");  
        
        if (!retValue || retValue.trim()== '') {
        	  alert("没有输入站点名称，无法创建");
        	  return false;
        }
        
        document.getElementById('dAaFileName').value = retValue.trim();
        return true;
     }
      
     String.prototype.trim = function(){
          return this.replace(/(^s*)|(s*$)/g, "");
      }       
   </script>
</HEAD>
<BODY  onload = 'reMoveLoading();' >


<DIV>
  <TABLE height="100%" cellSpacing=0 cellPadding=0 width="100%" border=0>
    <TBODY>
      <TR>
        <TD   vAlign=top>
<!-- -------------------------form--------------------------  -->
           <form action="website.php" method="get" name="websiteForm" target="_self">
             <div style="width:100%; text-align:right;">
             	   <?php
             	       if (!$dbConnectErr) {
             	          echo('  <input type="submit" name="addWeb" value="创建子站点" onclick="return inputName()"/> ');
             	       }
             	   ?>       	 
             </div>		   
             <DIV style="text-align:left; height:320px;overflow:auto">
                <TABLE class=gridView id="websiteTbl"
                  style="WIDTH:100%; BORDER-COLLAPSE: collapse" cellSpacing=0 rules=all border=1>
                       <?php
                           if (!$pathErr) {
                              if ($size > 0) {
                            	   createTitle();
                                 for ($i = 0; $i < $size; $i++) {
                                      createRow($files[$i],$createFlg[$i]);
                                 }
                              } 
                           } 
                       ?>   
                </TABLE>
             </DIV>

             <input type="hidden" name="dAaFileName"/>
             <input type="hidden" name="operate" value="cretate"/>
          </form>
<!-- -------------------------form--------------------------  -->        </TD>
        <TD width="10" style="BACKGROUND-IMAGE: url(../images/main_rs.gif)"></TD>
      </TR>
      <TR 
  style="BACKGROUND-IMAGE: url(../images/main_fs.gif); BACKGROUND-REPEAT: repeat-x" 
  height=10>
        <TD style="BACKGROUND-IMAGE: url(../images/main_fs.gif)"></TD>
        <TD style="BACKGROUND-IMAGE: url(../images/main_rf.gif)"></TD>
      </TR>
    </TBODY>
  </TABLE>
</DIV>

  <?php
      if ($dbConnectErr) {
          echo("<script>alert('连接数据库失败，请在info.php文件设置正确的信息')</script>");
      }
   
      if ($pathErr) {
          echo("<script>alert('指定网站路径有误，请在info.php文件中重设路径')</script>");
      }
      if ($fileCreateErr){
          echo("<script>alert('创建子站点${newFileName}失败，请重新试一下')</script>");
      }
      if ($modifyConfigErr){
         echo("<script>alert('修改子站点${newFileName}配置文件失败，请确认父站点文件是否完整')</script>");
      }
      if ($fileDeleteErr){
          echo("<script>alert('删除子站点${deleteFileName}失败，请重新试一下')</script>");
      }  
      
      if ($addViewErr){
          echo("<script>alert('创建子站点${deleteFileName}视图和表失败')</script>");
      }   
      
      if ($delViewErr){
          echo("<script>alert('删除子站点${deleteFileName}视图和表失败')</script>");
      }
      
      if ($queryWebErr){
          echo("<script>alert('查询子站点失败')</script>");
      }
      
      if ($webCreateErr) {
          echo("<script>alert('创建子站点失败')</script>");
      }      
  ?>
  
</BODY>
</HTML>
